// src/stores/order.js
import { defineStore } from 'pinia'
import axios from 'axios'
import { ref } from 'vue'

export const useOrderStore = defineStore('order', () => {
  const orders = ref([])

  const fetchOrders = async () => {
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        console.warn('未登录，无法获取订单列表')
        orders.value = []
        return { success: false, data: [], message: '未登录' }
      }
      
      // 从服务器获取订单（两个项目共用3002端口，所以只需要调用一次）
      const res = await axios.get('/api/admin/orders', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      if (res.data && res.data.success) {
        orders.value = res.data.data || []
        // 按创建时间倒序排序
        orders.value.sort((a, b) => {
          const timeA = new Date(a.createdAt || 0).getTime()
          const timeB = new Date(b.createdAt || 0).getTime()
          return timeB - timeA
        })
        
        console.log('成功获取订单列表，订单数量:', orders.value.length)
        return { success: true, data: orders.value }
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      if (error.response?.status === 401) {
        console.warn('未授权，请重新登录')
      } else if (error.response?.status === 403) {
        console.warn('权限不足，需要管理员权限')
      }
      orders.value = []
      return { success: false, data: [] }
    }
  }

  // 获取订单统计
  const getOrderStats = () => {
    const allOrders = orders.value || []
    
    const stats = {
      totalOrders: allOrders.length,
      pendingOrders: allOrders.filter(o => o.status === 'pending').length,
      processingOrders: allOrders.filter(o => o.status === 'processing').length,
      shippedOrders: allOrders.filter(o => o.status === 'shipped').length,
      completedOrders: allOrders.filter(o => o.status === 'completed').length,
      cancelledOrders: allOrders.filter(o => o.status === 'cancelled').length,
      totalRevenue: allOrders
        .filter(o => o.status === 'completed')
        .reduce((sum, o) => sum + (o.totalPrice || 0), 0)
    }
    
    return stats
  }

  return {
    orders,
    fetchOrders,
    getOrderStats
  }
})


